package com.qire.manhua.dialog;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.qire.antsrouter.lifecycleHandler.ActivityManageHandler;
import com.qire.common.support.base.BaseDialog;
import com.qire.common.utils.EquipmentInfoUtil;
import com.qire.common.utils.Logger;
import com.qire.manhua.R;
import com.qire.common.model.enumeration.RewardType;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * 领取任务奖励结果弹窗：在任务中心页领取奖励后弹出
 */
public class ReceiveTaskRewardsDialog extends BaseDialog {
    private final RecycledDrawable[] frameDrawable = new RecycledDrawable[2];
    private final LinearLayout rootLayout;
    private final ImageView frameImageView;
    private final TextView titleTextView;
    private final TextView tipsTextView;
    private final ImageView confirmIconView;
    private final TextView confirmTextView;
    private final LinearLayout confirmButton;
    private final TextView cancelTextView;

    private CharSequence titleText   = "领取成功";
    private CharSequence tipsText    = "+10金豆";
    private CharSequence confirmText = "双倍领取";
    private CharSequence cancelText  = "放弃双倍奖励!";

    private boolean isDouble = false;
    private View.OnClickListener confirmBtnListener;

    private ReceiveTaskRewardsDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
        rootLayout      = new LinearLayout(context);
        frameImageView  = new ImageView(context);
        titleTextView   = new TextView(context);
        tipsTextView    = new TextView(context);
        confirmIconView = new ImageView(getContext());
        confirmTextView = new TextView(getContext());
        confirmButton   = new LinearLayout(context);
        cancelTextView  = new TextView(context);
    }

    private void initChildView(){

        int imgWidth    = frameDrawable[0].getBounds().width();
        int imgHeight   = frameDrawable[0].getBounds().height();
        LayoutParams frameImageViewLP = new LayoutParams(imgWidth,imgHeight);
        frameImageView.setBackgroundColor(Color.TRANSPARENT);

        initTitleTextView();
        initTipsTextView();
        initConfirmButton();
        initCancelTextView();

        refreshUI();

        rootLayout.addView(frameImageView,frameImageViewLP);
        rootLayout.addView(titleTextView);
        rootLayout.addView(tipsTextView);
        rootLayout.addView(confirmButton);
        rootLayout.addView(cancelTextView);
    }

    private void initTitleTextView(){
        titleTextView.setText(titleText);
        titleTextView.setTextSize(30);
        titleTextView.setTypeface(Typeface.DEFAULT_BOLD);
        titleTextView.setTextColor(Color.WHITE);
        LayoutParams titleTextLP = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
//        titleTextLP.topMargin = EquipmentInfoUtil.dip2px(8);
        titleTextView.setLayoutParams(titleTextLP);
    }

    private void initTipsTextView(){
        tipsTextView.setText(tipsText);
        tipsTextView.setTextSize(21);
        tipsTextView.setTextColor(Color.rgb(0xff,0xd9,0x46));
        LayoutParams tipsTextLP = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        tipsTextLP.topMargin = EquipmentInfoUtil.dip2px(16);
        tipsTextView.setLayoutParams(tipsTextLP);
    }

    private void initConfirmButton(){
        confirmIconView.setImageResource(R.drawable.app_task_center_icon_video);
        LayoutParams iconViewLP = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        iconViewLP.rightMargin  = EquipmentInfoUtil.dip2px(5);
        confirmIconView.setLayoutParams(iconViewLP);

        confirmTextView.setText(confirmText);
        confirmTextView.setTextSize(16);
        confirmTextView.setTextColor(Color.rgb(0x42,0x33,0x00));

        LayoutParams confirmLP = new LayoutParams(EquipmentInfoUtil.dip2px(160),EquipmentInfoUtil.dip2px(43));
        confirmLP.topMargin = EquipmentInfoUtil.dip2px(38);
        confirmButton.setLayoutParams(confirmLP);
        confirmButton.setGravity(Gravity.CENTER);
        confirmButton.setOrientation(LinearLayout.HORIZONTAL);
        confirmButton.setBackgroundResource(R.drawable.app_task_center_button_double_receive);
        confirmButton.addView(confirmIconView);
        confirmButton.addView(confirmTextView);

        confirmButton.setOnClickListener(view -> {
            if(confirmBtnListener != null) {
                confirmBtnListener.onClick(view);
            }
            dismiss();
        });
    }

    private void initCancelTextView(){
        cancelTextView.setText(cancelText);
        cancelTextView.setTextSize(14);
        cancelTextView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);//下划线
        cancelTextView.getPaint().setAntiAlias(true);//抗锯齿
        cancelTextView.setTextColor(Color.WHITE);
        cancelTextView.setOnClickListener((View view) -> dismiss());

        LayoutParams cancelLP = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        cancelLP.topMargin = EquipmentInfoUtil.dip2px(14);
        cancelTextView.setLayoutParams(cancelLP);
    }

    private void initLayout(){
        rootLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        rootLayout.setBackgroundColor(Color.TRANSPARENT);
        rootLayout.setOrientation(LinearLayout.VERTICAL);
        rootLayout.setGravity(Gravity.CENTER);
//        rootLayout.setOnClickListener((View view)->dismiss());

        LayoutParams layoutParams= new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        layoutParams.gravity = Gravity.CENTER;
        setContentView(rootLayout,layoutParams);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initLayout();
        initChildView();
        setGravityCenter(this);
    }

    private void setGravityCenter(Dialog dialog){
        Window window = dialog.getWindow();
        window.setGravity(Gravity.CENTER);
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.height = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(params);
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    }

    private void refreshUI() {
        confirmIconView.setVisibility(isDouble ? View.VISIBLE : View.GONE);
        cancelTextView.setVisibility(isDouble ? View.VISIBLE : View.GONE);
        setConfirmText(isDouble ? "双倍领取" : "我知道了");
    }

    public ReceiveTaskRewardsDialog setTitleText(CharSequence titleText){
        this.titleText = titleText;
        titleTextView.setText(titleText);
        return this;
    }

    public ReceiveTaskRewardsDialog setTipsText(CharSequence tipsText){
        this.tipsText = tipsText;
        tipsTextView.setText(tipsText);
        return this;
    }
    public ReceiveTaskRewardsDialog setConfirmText(CharSequence confirmText){
        this.confirmText = confirmText;
        confirmTextView.setText(confirmText);
        return this;
    }

    public ReceiveTaskRewardsDialog setDouble(boolean isDouble){
        this.isDouble = isDouble;
        refreshUI();
        return this;
    }

    public ReceiveTaskRewardsDialog setConfirmBtnListener(View.OnClickListener confirmBtnListener){
        this.confirmBtnListener = confirmBtnListener;
        return this;
    }

    //倒计时
    private CountDownTimer timer = new CountDownTimer(Integer.MAX_VALUE/*2*1000*/, 200) {
        int index = 0;
        @Override
        public void onTick(long l) {
            frameImageView.setImageDrawable(frameDrawable[(index++)%2]);
        }

        @Override
        public void onFinish() {
            if(isShowing())
                dismiss();
        }
    };

    @Override
    public void show() {
        super.show();
        timer.start();
    }

    @Override
    protected void onStop() {
        super.onStop();
        //TODO:此处会在dismiss()窗口时调用，但并非我所想的在Dialog完全退出时才调用，有待解决，复用Dialog时，第一次show可以显示，第2次可能就没有图片了。
        for(RecycledDrawable recycledDrawable : frameDrawable){
            recycledDrawable.recycled();
        }
        Logger.i("ReceiveTaskRewardsDialog: 图片资源被释放~~");
        timer.cancel();
    }

    public static class Builder{

        public static ReceiveTaskRewardsDialog builder(RewardType rewardType) {
            return builder(ActivityManageHandler.HANDLER.currentActivity(), rewardType);
        }
        public static ReceiveTaskRewardsDialog builder(Context context, RewardType rewardType) {
            ReceiveTaskRewardsDialog dialog = new ReceiveTaskRewardsDialog(context, R.style.CustomDialog_NoPadding);
            int rid1 = (rewardType == RewardType.Vip) ? R.drawable.app_task_center_receive_vip1 : R.drawable.app_task_center_receive_bean1;
            int rid2 = (rewardType == RewardType.Vip) ? R.drawable.app_task_center_receive_vip2 : R.drawable.app_task_center_receive_bean2;
            dialog.frameDrawable[0] = new RecycledDrawable(BitmapFactory.decodeResource(context.getResources(),rid1));
            dialog.frameDrawable[1] = new RecycledDrawable(BitmapFactory.decodeResource(context.getResources(),rid2));
            return dialog;
        }

    }

    private static class RecycledDrawable extends Drawable {
        private final Paint mBitmapPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        private Bitmap mDrawBitmap;
        private volatile boolean isRecycled = false;

        public RecycledDrawable(Bitmap drawBitmap){
            mBitmapPaint.setDither(true);
            mDrawBitmap = drawBitmap;
            setBounds(0,0,mDrawBitmap.getWidth(),mDrawBitmap.getHeight());
        }

        @Override
        public void draw(@NonNull Canvas canvas) {
            if(!isRecycled)
                canvas.drawBitmap(mDrawBitmap,0,0,mBitmapPaint);
        }

        @Override
        public void setAlpha(@Nullable int alpha) {
            mBitmapPaint.setAlpha(alpha);
            invalidateSelf();
        }

        @Override
        public void setColorFilter(@Nullable ColorFilter colorFilter) {
            mBitmapPaint.setColorFilter(colorFilter);
            invalidateSelf();
        }

        @Override
        public int getOpacity() {
            return PixelFormat.TRANSLUCENT;
        }

        public void recycled(){
            if(!isRecycled) {
                isRecycled = true;
                mDrawBitmap.recycle();
                mDrawBitmap = null;
            }
        }

    }
}
